<?php
namespace api\web\controller;

use api\web\model\AddressModel;
use api\web\model\OrderModel;
use api\web\model\GoodsModel;
use cmf\controller\RestBaseController;
use think\Request;

class OrderController extends RestBaseController
{
    public function order(Request $request)
    {
        $data = input('post.');

        // 查询商品
        $goods = GoodsModel::where('id', $data['goods_id'])->find();
        if (!$goods) {
            $this->error('商品不存在');
        }
        if ($goods['switch'] != 1) {
            $this->error('商品缺货或者已下架');
        }

        $goods_info = $this->getGoodsInfo2($goods, $data['goods_info']);
        if (!$goods_info) {
            $this->error('商品规格不存在');
        }
        $price = $goods_info['单价'];

        $address = AddressModel::where('id', $data['address_id'])->find();
        if (!$address) {
            $this->error('地址不存在');
        }

        $insert_data = [
            'user_id' => $request->userId,
            'goods_name' => $goods['title'],
            'goods_info' => json_encode($data['goods_info']),
            'price' => $price,
            'num' => $data['num'],
            'total_price' => round($price * $data['num'], 2),
            'trade_no' => date('YmdHis') . mt_rand(1111, 9999) . createRandStr(4),
            'user_name' => $address['name'],
            'user_tel' => $address['mobile'],
            'user_address' => $address['location'] . $address['address'],
            'pay_type' => $data['pay_type'],
            'status' => 0,
            'remarks' => $data['remarks'],
            'create_time' => date('Y-m-d H:i:s'),
        ];

        $model = new OrderModel();
        $create = $model->save($insert_data);
        if ($create){
            $this->success('订单创建成功',[
                'payInfo' => [
                    'order_id' => $model->id
                ]
            ]);
        }else {
            $this->error('订单创建失败');
        }

    }

    protected function getGoodsInfo($goods, $sku)
    {
        $spuSku = json_decode($goods['info'], true);

        $spu_info = '';
        foreach ($spuSku as $val) {
            if ($val['尺码'] == $sku['尺码'] && $val['颜色'] == $sku['颜色']) {
                $spu_info = $val;
            }
        }
        return $spu_info;
    }

    protected function getGoodsInfo2($goods, $sku)
    {
        $spuSku = json_decode($goods['info'], true);

        //循环的商品的规格
        foreach ($spuSku as $sk) {
            $hasSku = true;
            //购买的规格
            foreach ($sku as $attr => $val) {
                if ($sk[$attr] != $val) {
                    $hasSku = false;
                    break;
                }
            }
            if ($hasSku) {
                return $sk;
            }
        }

        return null;
    }

    public function wuliu()
    {
        $LogisticCode = input('post.LogisticCode');
        $contentType = 'form';
        $url = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';
        $RequestData = [
            'LogisticCode' => $LogisticCode
        ];
        $RequestDataJson = json_encode($RequestData);
        $apiKey = 'bc5ca0d1-a7ba-4d6f-a6d8-e215d88c8c65';
        $sign = urlencode(base64_encode(md5($RequestDataJson.$apiKey)));
        $param = [
            'RequestData' => $RequestDataJson,
            'RequestType'=> 8002,
            'EBusinessID' => 1855241,
            'DataSign' => $sign,
            'DataType' => 2
        ];
        $wu= $this->curlRequest('POST',$url,$contentType,$param);
        $this->success('查询成功',$wu);
    }


    // CURL
    protected function curlRequest($type, $url, $contentType, $data = [], $timeout = 60)
    {
        try {
            $type = strtoupper($type);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url); // 设置请求链接
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 不直接输出页面
            curl_setopt($curl, CURLOPT_HEADER, 0); // 获取响应头向下
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);   // 请求超时时间，单位：秒
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1');
            if (substr($url, 0, 5) == 'https') {
                // 自动判断是否是 https 提交
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                // https请求，不验证证书和 hosts
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            // 判断 Content-Type 类型
            if ($contentType == 'json') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
            }
            if ($contentType == 'form') {
                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
            }
            switch ($type) {
                case "GET" :
                    curl_setopt($curl, CURLOPT_HTTPGET, true);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, true);
                    if ($contentType == 'json') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
                    }
                    if ($contentType == 'form') {
                        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
                    }
                    break;
            }
            $result = curl_exec($curl);
            $err_code = curl_errno($curl);
            $curlInfo = curl_getinfo($curl);
            curl_close($curl);
            if ($err_code) {
                return ['status' => 'error', 'msg' => 'sendRequestError:' . $err_code];
            }
            if ($curlInfo['http_code'] == 200) {
                return json_decode($result, true);
            }
            return false;
        } catch (\Exception $e) {
            return ['status' => 'error', 'msg' => $e->getMessage()];
        }
    }
}
